var fs = true;
// 储存临时已扫描的条码
var scannedBarcodes = []; // 每个元素格式: { barcode: "条码编号", materialNo: "物料号", materialName: "物料名称" }

// 储存临时未扫描的物料
var StockList = [];
var UserName = localStorage.getItem("UserName");
mui.plusReady(function() {
	var currentwindow = plus.webview.currentWebview();
	if (currentwindow.TradeOrderNO != '' && currentwindow.TradeOrderNO != undefined) {
		$("#TradeOrderNO").val(currentwindow.TradeOrderNO);
		$("#MaterialCode").val(currentwindow.ProductNO);
		$("#SourceOrderNO").val(currentwindow.SourceOrderNO);
	} else {
		mui.toast("No parameters brought in。", {
			duration: '1000',
			type: 'div'
		});
	}

	GetStockList();

	BandCode();

	$("#all").html("");
	$("#all").html(
		'<a style="font-size:100px; color:#F27D48; display:block; text-align:center;" class="mui-icon mui-icon-search"></a><a class="mui-title" style="color:#808080; position: initial; margin: 0 auto; height:' +
		(window.screen.height - 380) + 'px">No data available at the moment</a>');
	$("#BarCode").focus();
	plus.nativeUI.closeWaiting();
	//显示当前页面
	//mui.currentWebview.show();
});

// 更新库存列表显示
function UpdateStockListDisplay() {
	$("#all").html(""); // 清空显示

	if (StockList.length === 0) {
		$("#all").html(
			'<a style="font-size:100px; color:#F27D48; display:block; text-align:center;" class="mui-icon mui-icon-search"></a><a class="mui-title" style="color:#808080; position: initial; margin: 0 auto; height:' +
			(window.screen.height - 480) + 'px">No data available at the moment</a>');
		return;
	}
	//StockList.sort((a, b) => a.StationNO.localeCompare(b.StationNO));
	StockList.sort((a, b) =>
		a.RState.localeCompare(b.RState, undefined, {
			numeric: true
		}) ||
		a.BarcodeNO.localeCompare(b.BarcodeNO)
	);
	StockList.forEach(item => {
		var itemClass = item.RState == "2" ? 'locked-item' : '';
		$("#all").append(
			`<li class="mui-table-view-cell ${itemClass}">
               <div class="list-title">Code:${item.BarcodeNO}&nbsp;&nbsp;&nbspQty:${item.Qty}</div>
               <div class="list-detail">LampNO:${item.LampNO}&nbsp;&nbsp;&nbspStrNO:${item.StorageNO}</div>
               <div class="list-detail">StationNO:${item.StationNO}</div>
            </li>`
		);
	});
}

//绑定扫码下架
function BandCode() {
	// 绑定 MaterialCode 输入框的 keyup 事件
	$("#BarCode").keyup(function(event) {
		event.preventDefault();
		// 检查是否按下了回车键（keyCode 13）
		if (event.keyCode == 13) {

			var BarCode = $("#BarCode").val();
			// 检查 BarCode 是否为空
			if (!BarCode) {
				mui.toast("Please scan the BarCode。", {
					duration: '1000',
					type: 'div'
				});
				$("#BarCode").focus();
				return;
			}
			if (BarCode.indexOf("||") !== -1) { // 或者用 includes("||")
				BarCode = BarCode.split("||")[0];
				//console.log("解析到的条码:", firstBarcode); 
			}
			$("#BarCode").val(BarCode);
			// 检查条码是否在StockList中
			var index = StockList.findIndex(item => item.BarcodeNO === BarCode);
			if (index === -1) {
				mui.toast("Barcode not found in current stock list", {
					duration: '1000',
					type: 'div'
				});
				Audios();
				$("#BarCode").val('');
				$("#BarCode").focus();
				return;
			}

			var datas = {
				Color: 0,
				LigthCheck: false,
				OrderNO: $("#TradeOrderNO").val(),
				Items: [{
					BarcodeNO: BarCode,
					TradebarcodeID: StockList[index].TradebarcodeID
				}]
			};
			// 发送请求
			xccFormPostAsync("api/PDA/GetStationCode", datas, function(data) {
				document.activeElement.blur();
				if (data.Code === 200) {
					//赋值
					$("#StationNO").val(StockList[index].StationNO);
					$("#CodeNO").val(StockList[index].BarcodeNO);
					//自动修改数组明细状态
					StockList[index].RState = "2";
					// 更新显示
					UpdateStockListDisplay();
					mui.toast("success", {
						duration: '1000',
						type: 'div'
					});
					$("#BarCode").val('');
					$("#BarCode").focus();
				}
			}, function(error) {});

		}
		$("#BarCode").focus();
	});
}



//获取需要下架的条码GetTradeInACBarCode
function GetStockList() {
	StockList = []; // 先清空
	xccFormPostAsync("api/PDA/GetTradeInBarCode", {
		TradeOrderNO: $("#TradeOrderNO").val(),
		RState: -1
	}, function(data) {
		if (data.Items != null && data.Items.length > 0) {
			$("#all").html(""); ////全部清空
			for (var i = 0; i < data.Items.length; i++) {
				var existingIndex = StockList.findIndex(item => item.BarcodeNO === data.Items[i].BarcodeNO);

				if (existingIndex === -1) {
					StockList.push({
						TradebarcodeID: data.Items[i].TradebarcodeID,
						BarcodeNO: data.Items[i].BarcodeNO,
						StationNO: data.Items[i].StationNO,
						LampNO: data.Items[i].LampNO,
						LampCode: data.Items[i].LampCode,
						StorageNO: data.Items[i].StorageNO,
						Qty: data.Items[i].Qty,
						RState: data.Items[i].RState
					});
				};
			}

			UpdateStockListDisplay();
			$("#BarCode").focus();
		}
	}, function(errr) {
		$("#all").html("");
		$("#all").html(
			'<a style="font-size:100px; color:#F27D48; display:block; text-align:center;" class="mui-icon mui-icon-search"></a><a class="mui-title" style="color:#808080; position: initial; margin: 0 auto; height:' +
			(window.screen.height - 480) + 'px">No data available at the moment</a>');
		StockList = [];
	})
}

//失败报警
function Audios() {
	var audio = new Audio('../../../fonts/baojin.mp3');

	audio.play();
}